package com.primaryedu.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;

import com.primaryedu.data.Config;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import static com.primaryedu.ui.app.growstep.PhotoUtil.calculateInSampleSize;

/*********************************************
 * 类说昄1�7 图片工具籄1�7
 *
 * @author jun.wang
 * @version 创建时间＄1�715-4-14 下午4:56:38
 */
public class ImageUtil {

    /**
     * 读取图片属�1ￄ1�7：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角ￄ1�7�1�7
     */
    public static int readPictureDegree(String path) {
        int degree

                = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation =

                    exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,

                            ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 保存Bitmap对象到本地sdcard
     */
    public static void saveToSdcard(Bitmap bitmap, String path) {
        FileOutputStream fos = null;
        try {

            createFile(Environment.getExternalStorageDirectory()
                    + Config.head_image_url);
            Log.d("TAG",
                    "save path=" + Environment.getExternalStorageDirectory()
                            + Config.head_image_url);

            System.out.println("path==" + Environment.getExternalStorageDirectory()
                    + Config.head_image_url);
            File f = new File(Environment.getExternalStorageDirectory(), path);

            if (f.exists()) {
                f.delete();
            }
            fos = new FileOutputStream(f);
            if (null != fos) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存Bitmap对象到本地sdcard
     */
    public static void saveToSdcard(Bitmap bitmap) {
        saveToSdcard(bitmap, Config.head_image_url + "temp_photo.jpg");
    }

    /**
     * ɾ��ͷ����ʱ�ļ� description:
     */
    public static void deleteFile() {
        File file = new File(Config.SDPATH_HEAD + "temp_photo.jpg");

        if (file.exists()) {
            file.delete();
        }

    }

    /**
     * 创建丄1�7个目彄1�7
     */
    private static void createFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
//			file.mkdir();
            file.mkdirs();
        }
    }

    /**
     * 从本地图片路径得到Bitmap对象
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 裁剪图片，防止OOM
     *
     * @param 上下文
     * @param 图片资源
     * @param 裁剪比例
     * @return
     * @author Stone
     */
    public static Bitmap tailorBitmap(Context context, int resId, int ratio) {
        InputStream is = context.getResources().openRawResource(resId);

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = false;

        options.inSampleSize = ratio;

        Bitmap btp = BitmapFactory.decodeStream(is, null, options);
        return btp;
    }

    /**
     * 节省内存方式读取图片，防止OOM
     *
     * @param 上下文
     * @param 图片资源
     * @return
     * @author Stone
     */
    public static Bitmap readBitMap(Context context, int resId) {

        BitmapFactory.Options opt = new BitmapFactory.Options();

        opt.inPreferredConfig = Bitmap.Config.RGB_565;

        opt.inPurgeable = true;

        opt.inInputShareable = true;

        // 获取资源图片

        InputStream is = context.getResources().openRawResource(resId);

        return BitmapFactory.decodeStream(is, null, opt);

    }

    /*
    * 调用压缩图片的方法，返回压缩后的图片path
    *
    * */
    public static String compressImage(String filePath, String targetPath, int quality) {
        Bitmap bm = getSmallBitmap(filePath);//获取一定尺寸的图片
        int degree = readPictureDegree(filePath);//获取相片拍摄角度
        if (degree != 0) {//旋转照片角度，防止头像横着显示
            bm = rotateBitmap(bm, degree);
        }
        File outputFile = new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
            } else {
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
        } catch (Exception e) {
        }
        return outputFile.getPath();
    }

    /**
     * 根据路径获得图片信息并按比例压缩，返回bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 旋转照片
     *
     * @param bitmap
     * @param degress
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }
}
